<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>招标文件分析系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .step {
            margin-bottom: 30px;
            padding: 20px;
            border: 2px solid #e1e8ed;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .step.active {
            border-color: #667eea;
            background-color: #f8f9ff;
        }

        .step.completed {
            border-color: #28a745;
            background-color: #f8fff9;
        }

        .step-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }

        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .upload-area:hover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }

        .upload-area.dragover {
            border-color: #667eea;
            background-color: #f0f4ff;
        }

        .upload-icon {
            font-size: 48px;
            color: #ccc;
            margin-bottom: 15px;
        }

        .file-input {
            display: none;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
            display: inline-block;
            text-decoration: none;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }

        .file-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            margin-top: 15px;
            display: none;
        }

        .progress-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-top: 15px;
            display: none;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s ease;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
            display: none;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .result-container {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-top: 15px;
            display: none;
        }

        .result-content {
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            background: white;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #dee2e6;
            max-height: 400px;
            overflow-y: auto;
        }

        .file-link {
            color: #667eea;
            text-decoration: none;
            border-bottom: 1px dashed #667eea;
            transition: all 0.3s ease;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .file-link:hover {
            color: #764ba2;
            border-bottom-color: #764ba2;
            background-color: rgba(102, 126, 234, 0.1);
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        .download-icon {
            font-size: 14px;
        }
        
        .result-content .file-link {
            word-break: break-all;
            max-width: 100%;
        }

        .status-running {
            color: #ffc107;
        }

        .status-success {
            color: #28a745;
        }

        .status-error {
            color: #dc3545;
        }

        .hidden {
            display: none;
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid transparent;
            border-radius: 4px;
        }

        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        .alert-success {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>招标文件分析系统</h1>
            <p>上传文件，智能分析招标文档内容</p>
        </div>

        <div class="content">
            <!-- 错误提示 -->
            <div id="errorAlert" class="alert alert-danger hidden">
                <strong>错误！</strong> <span id="errorMessage"></span>
            </div>

            <!-- 成功提示 -->
            <div id="successAlert" class="alert alert-success hidden">
                <strong>成功！</strong> <span id="successMessage"></span>
            </div>

            <!-- 步骤1: 文件上传 -->
            <div class="step active" id="step1">
                <div class="step-title">步骤 1: 选择并上传文件</div>
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📁</div>
                    <p>点击选择文件或拖拽文件到此处</p>
                    <p style="font-size: 14px; color: #666; margin-top: 10px;">支持 PDF、DOC、DOCX 等格式</p>
                    <input type="file" id="fileInput" class="file-input" accept=".pdf,.doc,.docx,.txt">
                </div>

                <div class="file-info" id="fileInfo">
                    <strong>已选择文件：</strong>
                    <div id="fileName"></div>
                    <div id="fileSize"></div>
                    <button class="btn" id="uploadBtn" style="margin-top: 15px;">上传文件</button>
                </div>

                <div class="progress-container" id="uploadProgress">
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    <div id="progressText">上传中...</div>
                </div>
            </div>

            <!-- 步骤2: 分析执行 -->
            <div class="step" id="step2">
                <div class="step-title">步骤 2: 执行文件分析</div>
                <p>文件上传成功，点击下方按钮开始分析</p>
                <div id="fileUploadResult" style="margin: 15px 0;"></div>
                <button class="btn" id="analyzeBtn" disabled>开始分析</button>
            </div>

            <!-- 步骤3: 分析结果 -->
            <div class="step" id="step3">
                <div class="step-title">步骤 3: 分析结果</div>
                <div id="analysisStatus">
                    <div class="spinner" id="loadingSpinner"></div>
                    <p id="statusText">等待分析任务...</p>
                </div>

                <div class="result-container" id="resultContainer">
                    <h4>分析结果：</h4>
                    <div class="result-content" id="resultContent"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        class BidAnalysisApp {
            constructor() {
                this.fileData = null;
                this.executeId = null;
                this.pollingInterval = null;
                this.initializeEventListeners();
            }

            initializeEventListeners() {
                const uploadArea = document.getElementById('uploadArea');
                const fileInput = document.getElementById('fileInput');
                const uploadBtn = document.getElementById('uploadBtn');
                const analyzeBtn = document.getElementById('analyzeBtn');

                // 文件拖拽和点击上传
                uploadArea.addEventListener('click', () => fileInput.click());
                uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
                uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
                uploadArea.addEventListener('drop', this.handleDrop.bind(this));

                fileInput.addEventListener('change', this.handleFileSelect.bind(this));
                uploadBtn.addEventListener('click', this.uploadFile.bind(this));
                analyzeBtn.addEventListener('click', this.executeAnalysis.bind(this));
            }

            handleDragOver(e) {
                e.preventDefault();
                document.getElementById('uploadArea').classList.add('dragover');
            }

            handleDragLeave(e) {
                e.preventDefault();
                document.getElementById('uploadArea').classList.remove('dragover');
            }

            handleDrop(e) {
                e.preventDefault();
                document.getElementById('uploadArea').classList.remove('dragover');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    this.selectFile(files[0]);
                }
            }

            handleFileSelect(e) {
                const file = e.target.files[0];
                if (file) {
                    this.selectFile(file);
                }
            }

            selectFile(file) {
                this.fileData = file;
                document.getElementById('fileName').textContent = file.name;
                document.getElementById('fileSize').textContent = `文件大小: ${this.formatFileSize(file.size)}`;
                document.getElementById('fileInfo').style.display = 'block';
            }

            formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            async uploadFile() {
                if (!this.fileData) {
                    this.showError('请先选择文件');
                    return;
                }

                const formData = new FormData();
                formData.append('file', this.fileData);

                try {
                    document.getElementById('uploadProgress').style.display = 'block';
                    document.getElementById('uploadBtn').disabled = true;

                    const response = await fetch('/api/file/upload', {
                        method: 'POST',
                        body: formData
                    });

                    if (!response.ok) {
                        throw new Error(`上传失败: ${response.status} ${response.statusText}`);
                    }

                    const result = await response.json();
                    console.log('Upload response:', result); // 添加调试信息

                    // 检查多种可能的响应格式
                    if (result.code === 200 || result.success === true || result.status === 'success') {
                        // 尝试获取数据，支持多种可能的数据结构
                        const data = result.data || result.result || result;
                        if (data && (data.file_url || data.url) && (data.file_name || data.filename || data.name)) {
                            this.fileUploadSuccess(data);
                        } else {
                            console.error('Invalid data structure:', data);
                            throw new Error('返回数据格式不正确，缺少文件URL或文件名');
                        }
                    } else {
                        throw new Error(result.message || result.error || '上传失败');
                    }

                } catch (error) {
                    console.error('Upload error:', error);
                    this.showError(`文件上传失败: ${error.message}`);
                    document.getElementById('uploadBtn').disabled = false;
                } finally {
                    document.getElementById('uploadProgress').style.display = 'none';
                }
            }

            // 创建可下载的文件链接
            createDownloadableLink(url, fileName) {
                const isUrl = url && (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('/'));
                if (isUrl) {
                    return `<a href="${url}" class="file-link" target="_blank" download="${fileName}">
                        <span class="download-icon">📁</span>${fileName || url}
                    </a>`;
                }
                return fileName || url;
            }

            // 转换文本中的URL为可点击链接
            convertUrlsToLinks(text) {
                if (!text) return text;

                // URL正则表达式
                const urlRegex = /(https?:\/\/[^\s]+|\/[^\s]*\.[a-zA-Z0-9]+)/g;

                return text.replace(urlRegex, (url) => {
                    const fileName = url.split('/').pop() || url;
                    return `<a href="${url}" class="file-link" target="_blank" download="${fileName}">
                        <span class="download-icon">⬇️</span>${url}
                    </a>`;
                });
            }

            fileUploadSuccess(data) {
                console.log('Processing upload success with data:', data);

                // 标准化数据格式
                this.uploadedFileData = {
                    file_url: data.file_url || data.url,
                    file_name: data.file_name || data.filename || data.name
                };

                console.log('Normalized upload data:', this.uploadedFileData);

                // 更新步骤状态
                document.getElementById('step1').classList.remove('active');
                document.getElementById('step1').classList.add('completed');
                document.getElementById('step2').classList.add('active');

                // 创建可下载的文件链接
                const downloadableFileUrl = this.createDownloadableLink(
                    this.uploadedFileData.file_url,
                    this.uploadedFileData.file_name
                );

                // 显示上传结果
                document.getElementById('fileUploadResult').innerHTML = `
                    <div style="background: #e8f5e8; padding: 10px; border-radius: 4px;">
                        <strong>文件上传成功！</strong><br>
                        文件名: ${this.uploadedFileData.file_name}<br>
                        文件链接: ${downloadableFileUrl}
                    </div>
                `;

                // 启用分析按钮
                const analyzeBtn = document.getElementById('analyzeBtn');
                analyzeBtn.disabled = false;
                analyzeBtn.style.opacity = '1';
                analyzeBtn.style.cursor = 'pointer';

                console.log('Analyze button enabled:', !analyzeBtn.disabled);

                this.showSuccess('文件上传成功，可以开始分析了');
            }

            async executeAnalysis() {
                if (!this.uploadedFileData) {
                    this.showError('没有上传的文件数据');
                    return;
                }

                // 防重复点击 - 立即禁用按钮并显示加载状态
                const analyzeBtn = document.getElementById('analyzeBtn');
                if (analyzeBtn.disabled) {
                    return; // 如果已经在执行中，直接返回
                }

                try {
                    // 禁用按钮并更新显示状态
                    analyzeBtn.disabled = true;
                    analyzeBtn.textContent = '分析中...';
                    analyzeBtn.style.opacity = '0.6';
                    analyzeBtn.style.cursor = 'not-allowed';

                    console.log('Starting analysis with data:', this.uploadedFileData);

                    const requestData = {
                        file_url: this.uploadedFileData.file_url,
                        file_name: this.uploadedFileData.file_name
                    };

                    const response = await fetch('/api/bid-analysis/execute', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(requestData)
                    });

                    if (!response.ok) {
                        throw new Error(`分析执行失败: ${response.status} ${response.statusText}`);
                    }

                    const result = await response.json();
                    console.log('Analysis execute response:', result);

                    // 检查多种可能的响应格式
                    if (result.code === 200 || result.success === true) {
                        const executeId = result.data?.execute_id || result.execute_id;
                        if (executeId) {
                            this.executeId = executeId;
                            console.log('Got execute_id:', this.executeId);
                            this.startAnalysisPolling();
                        } else {
                            throw new Error('返回数据中缺少 execute_id');
                        }
                    } else {
                        throw new Error(result.message || result.error || '分析执行失败');
                    }

                } catch (error) {
                    console.error('Analysis execution error:', error);
                    this.showError(`分析执行失败: ${error.message}`);
                    // 恢复按钮状态
                    this.resetAnalyzeButton();
                }
            }

            resetAnalyzeButton() {
                const analyzeBtn = document.getElementById('analyzeBtn');
                analyzeBtn.disabled = false;
                analyzeBtn.textContent = '开始分析';
                analyzeBtn.style.opacity = '1';
                analyzeBtn.style.cursor = 'pointer';
            }

            startAnalysisPolling() {
                console.log('Starting analysis polling with execute_id:', this.executeId);

                // 更新步骤状态
                document.getElementById('step2').classList.remove('active');
                document.getElementById('step2').classList.add('completed');
                document.getElementById('step3').classList.add('active');

                // 显示加载状态
                document.getElementById('loadingSpinner').style.display = 'block';
                document.getElementById('statusText').textContent = '分析中，请稍候...';
                document.getElementById('statusText').className = 'status-running';

                // 清除可能存在的旧轮询
                if (this.pollingInterval) {
                    clearInterval(this.pollingInterval);
                }

                // 立即检查一次
                this.checkAnalysisResult();

                // 开始轮询 - 每3秒检查一次
                this.pollingInterval = setInterval(() => {
                    console.log('Polling analysis result...');
                    this.checkAnalysisResult();
                }, 3000);
            }

            async checkAnalysisResult() {
                if (!this.executeId) {
                    console.error('No execute_id available for polling');
                    this.analysisError('缺少执行ID，无法查询结果');
                    return;
                }

                try {
                    console.log(`Checking result for execute_id: ${this.executeId}`);

                    const response = await fetch(`/api/bid-analysis/result/${this.executeId}`);

                    if (!response.ok) {
                        throw new Error(`获取结果失败: ${response.status} ${response.statusText}`);
                    }

                    const result = await response.json();
                    console.log('Analysis result response:', result);

                    if (result.code === 200 || result.success === true) {
                        const status = result.data?.execute_status || result.execute_status;
                        console.log('Analysis status:', status);

                        if (status === 'Running') {
                            document.getElementById('statusText').textContent = '分析中，请稍候...';
                            document.getElementById('statusText').className = 'status-running';
                            // 继续轮询
                        } else if (status === 'Success') {
                            const resultData = result.data?.result?.data || result.result?.data || result.data;
                            this.analysisSuccess(resultData);
                        } else {
                            this.analysisError(`分析失败，状态: ${status}`);
                        }
                    } else {
                        this.analysisError(result.message || result.error || '获取分析结果失败');
                    }

                } catch (error) {
                    console.error('Check analysis result error:', error);
                    this.analysisError(`获取分析结果失败: ${error.message}`);
                }
            }

            analysisSuccess(resultData) {
                console.log('Analysis completed successfully:', resultData);

                // 停止轮询
                if (this.pollingInterval) {
                    clearInterval(this.pollingInterval);
                    this.pollingInterval = null;
                }

                // 隐藏加载状态
                document.getElementById('loadingSpinner').style.display = 'none';
                document.getElementById('statusText').textContent = '分析完成！';
                document.getElementById('statusText').className = 'status-success';

                // 显示结果，转换其中的URL为可点击链接
                document.getElementById('resultContainer').style.display = 'block';
                const processedResult = this.convertUrlsToLinks(resultData || '分析结果为空');
                document.getElementById('resultContent').innerHTML = processedResult;

                // 完成最后一步
                document.getElementById('step3').classList.remove('active');
                document.getElementById('step3').classList.add('completed');

                this.showSuccess('文件分析完成！');
            }

            analysisError(errorMessage) {
                console.error('Analysis failed:', errorMessage);

                // 停止轮询
                if (this.pollingInterval) {
                    clearInterval(this.pollingInterval);
                    this.pollingInterval = null;
                }

                // 隐藏加载状态
                document.getElementById('loadingSpinner').style.display = 'none';
                document.getElementById('statusText').textContent = '分析失败';
                document.getElementById('statusText').className = 'status-error';

                this.showError(errorMessage);

                // 恢复分析按钮状态，允许重试
                this.resetAnalyzeButton();
            }

            showError(message) {
                document.getElementById('errorMessage').textContent = message;
                document.getElementById('errorAlert').classList.remove('hidden');
                document.getElementById('successAlert').classList.add('hidden');

                // 3秒后自动隐藏
                setTimeout(() => {
                    document.getElementById('errorAlert').classList.add('hidden');
                }, 5000);
            }

            showSuccess(message) {
                document.getElementById('successMessage').textContent = message;
                document.getElementById('successAlert').classList.remove('hidden');
                document.getElementById('errorAlert').classList.add('hidden');

                // 3秒后自动隐藏
                setTimeout(() => {
                    document.getElementById('successAlert').classList.add('hidden');
                }, 3000);
            }
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            new BidAnalysisApp();
        });
    </script>
</body>
</html>
